<script type="text/javascript">
    //adding load class to body and hide page
    document.documentElement.className += 'loadstate';
</script>
<script>
    retour = false
    articles = []
    retours = []
    paiements = []
    accomptes = []
    client_id = 1
    limite_credit = 0
    solde = 0
    client_old = 1
    function stockSearch(articles, id) {


        for (var i = 0; i < articles.length; i++) {
            if (articles[i].id == id) {
                return i;
            }
        }
        return -1;
    }

</script>
<style>
    #content{
        padding-bottom:0px;
    }
    body{
        padding-bottom: 0px;
    }
</style>
<div class="contentwrapper">
    <div class="row-fluid">
        <div style="width: 100%" class="span6">
            <div class="box">
                <div class="title">
                    <h4>
                        <span class="icon16 brocco-icon-grid"></span>
                        <span>Information General</span>
                    </h4>
                </div>
                <div class="content">
                    <div class="row-fluid">
                        <div class="span12">

                            <table style="width: 100%">
                                <tr>
                                    <td style="width: 30%">
                                        <label>Date:</label>
                                        <div>
                                            <input id="date" type="text"  readonly/><input type="hidden" id="heure"/>
                                            <input id="now" type="text" style="width: 70px;" readonly/>
                                            <img src="/images/start.jpg" height="30" width="30" style="display: none;" id="start"> 
                                            <img src="/images/previous.jpg" height="30" width="30" style="display: none;" id="prev"> 
                                        </div>
                                    </td>
                                    <td  style="width: 20%">
                                        <label>Client:</label>
                                        <div id="div_client" class="span8 controls" style="width: 200px">

                                            <div id='client'>
                                            </div>
                                            <script>
                                                var url = '{{path('gds_list_client_select')}}';
                                                var source =
                                                        {
                                                            datatype: "json",
                                                            datafields: [
                                                                {name: 'id'},
                                                                {name: 'raison_social'},
                                                                {name: 'limite_credit'},
                                                                {name: 'solde'}
                                                            ],
                                                            url: url,
                                                            async: false
                                                        };
                                                var dataAdapter = new $.jqx.dataAdapter(source);
                                                $("#client").jqxComboBox({selectedIndex: 0, source: dataAdapter, displayMember: "raison_social", valueMember: "id", width: 200, height: 25});
                                                $("#client").on('select', function(event) {
                                                    if (event.args) {
                                                        var item = event.args.item;
                                                        if (item) {
                                                            client_id = item.value
                                                            limite_credit = item.credit
                                                            solde = item.solde
                                                            var valueelement = $("<div></div>");
                                                            valueelement.text("Value: " + item.value);
                                                            var labelelement = $("<div></div>");
                                                            labelelement.text("Label: " + item.label);
                                                            $("#selectionlog").children().remove();
                                                            $("#selectionlog").append(labelelement);
                                                            $("#selectionlog").append(valueelement);
                                                        }
                                                    }
                                                });
                                                $('.jqx-widget-content').blur(function() {
                                                    if (client_old != client_id)
                                                    {
                                                        changerClient()
                                                        client_old = client_id
                                                    }

                                                })


                                            </script>

                                        </div> 
                                    </td>
                                    <td  style="width: 20%">
                                        <label>Departement:</label>
                                        <div class="span8 controls" style="width: 200px">
                                    {{ render(controller('GdsVenteBundle:Devis:getAllDepartement')) }}
                                        </div> 
                                    </td>
                                                {% if(is_granted('ROLE_ADMIN')) %}
                                    <td  style="width: 20%">
                                        <label>Caisse:</label>
                                        <select id="caisse" >
{% for caisse in caisses %}
                                            <option value="{{caisse.id}}">{{caisse}}</option>
        {% endfor %}
                                        </select>
                                    </td>
                                            {% endif %}

                                </tr>

                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>

    <div class="row-fluid">
        <div  style="width: 48.7179%" class="span6">
            <div style="margin-bottom: 0" class="box">
                <div class="title">
                    <h4>
                        <span class="icon16 brocco-icon-grid"></span>
                        <span>Articles</span>
                    </h4>
                </div>
                <div id="content_list_article" class="content">
                    <div class="row-fluid">
                        <div class="span12">
                            <table id="lignes_ticket" cellpadding="0" cellspacing="0" border="0" class="responsive  display table table-bordered" width="100%">
                                <thead>
                                    <tr >
                                        <th>N°</th>
                                        <th>Reference</th>
                                        <th>Designation</th>
                                        <th>Qte</th>
                                        <th>Remise</th>
                                        <th>Total</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody id="gds_ventebundle_lignedevistype">
                                </tbody>
                                <tbody>
                                    <tr>
                                        <th colspan="7" style="text-align: center">Retour</th>
                                    </tr>
                                </tbody>
                                <tbody id="gds_vente_retour">

                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th colspan="3" style="text-align: right">Total :</th>
                                        <th id="quantite_total">0</th>
                                        <th></th>
                                        <th colspan="2" id="ttc_total">0.000</th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <div id="content_form_article" style="width: 48.7179%" class="span6">
            <div  class="box">
                <div class="title">
                    <h4>
                        <span class="icon16 brocco-icon-grid"></span>
                        <span>Ajouter Article</span><span style="float: right;margin-right: 20px"><button id="btn_retour" class="btn btn-info">Retour</button>   </span>
                    </h4>
                </div>
                <div  class="content">
                    <form class="form-horizontal" action="javascript:addLigne(false)">
                        <input id="article_id" type="hidden" />
                        <div class="form-row row-fluid">
                            <div class="span12">
                                <div class="row-fluid">
                                    <label class="form-label span4" for="normal">Famille</label>
                                    <div style="margin-left: 0px;margin-bottom: 3px" class="span8" id="td_familles">
                                        <input id="familles" class="span8 text" type="text" />
                                    </div>
                                </div>
                                <div class="row-fluid">
                                    <label class="form-label span4" for="normal">Sous famille</label>
                                    <div style="margin-left: 0px;margin-bottom: 3px" class="span8" id="td_sous_familles">
                                        <input id="sous_familles" class="span8 text" type="text" />
                                    </div>
                                </div>
                                <div class="row-fluid">
                                    <label class="form-label span4" for="normal">Article</label>
                                    <div style="margin-left: 0px;margin-bottom: 3px" class="span8" id="td_articles">
                                        <input id="articles" class="span8 text" type="text" />
                                    </div>
                                </div>
                                <div class="row-fluid">
                                    <label class="form-label span4" for="normal">Quantite</label>
                                    <div id="div_article_quantite"><input id="article_quantite" class="span8 text" type="text" /></div>
                                </div>
                                <div class="row-fluid">
                                    <label class="form-label span4" for="normal">Remise</label>
                                    <input id="article_remise" class="span8 text" type="text" />
                                </div>
                                <div class="row-fluid">
                                    <label class="form-label span4" for="normal">Prix Vente Ttc</label>
                                    <input id="article_prix_ttc" class="span8 text" type="text" />
                                </div>
                            </div>
                        </div>
                        <div class="form-actions">
                            <button class="btn btn-info" type="submit">Ajouter</button>
                            <button onclick="resetFormArticle()" class="btn" type="button">Annuler</button>
                        </div>
                    </form>
                    <script>
                        $('#btn_retour').click(function() {

                            if (retour)
                                $(this).html('Retour')
                            else
                                $(this).html('Achat')
                            retour = !retour
                        })

                        $('#article_quantite').dblclick(function() {
                            $.msgBox({
                                title: "Dépassement de la quantités minimale",
                                content: "mdp: <input id='mdp' type='password' />",
                                type: "confirm",
                                buttons: [
                                    {type: "submit", value: "Valider"},
                                    {type: "cancel", value: "Annuler"}
                                ],
                                afterShow: function() {
                                    $('#mdp').focus()
                                },
                                success: function(result) {
                                    if (result == "Valider") {
                                        if ($('#mdp').val() != '') {
                                            $.ajax({
                                                url: "{{ path('gds_vente_quantite_depasse') }}",
                                                data: 'pass_quantite=' + $('#mdp').val(),
                                                success: function(data) {
                                                    if (data != 'failed') {
                                                        $('#article_quantite').spinner({
                                                            min: 0,
                                                            max: 99999,
                                                            step: 1,
                                                            places: 2,
                                                            showOn: 'both'
                                                        });
                                                        $('#article_quantite').focus()
                                                    }
                                                }
                                            })
                                        }
                                    }
                                }
                            });
                        })
                        familles = []
                        sous_familles = []
                        article = new Object()
                        $.ajax({
                            url: '{{path('gds_vente_get_all_familles')}}',
                            datatype: 'json',
                            success: function(data) {
                                $('#familles').tokenInput(data, {
                                    preventDuplicates: true,
                                    onAdd: function(item) {
                                        familles[familles.length] = item.id
                                        chercherSousFamilles()
                                        chercherArticles('famille')
                                    },
                                    onDelete: function(item) {
                                        familles.splice($.inArray(item.id, familles), 1);
                                        chercherSousFamilles()
                                        chercherArticles('famille')
                                    },
                                });
                            }
                        })
                        $('#sous_familles').tokenInput('', {
                            preventDuplicates: true
                        });
                        function chercherSousFamilles() {
                            $('#td_sous_familles ul').remove()
                            $.ajax({
                                url: '{{path('gds_vente_get_sous_familles_where_familles')}}',
                                datatype: 'json',
                                data: 'familles={"familles":' + JSON.stringify(familles) + '}',
                                success: function(data) {
                                    $('#sous_familles').tokenInput(data, {
                                        preventDuplicates: true,
                                        onAdd: function(item) {
                                            sous_familles[sous_familles.length] = item.id
                                            chercherArticles('sous')
                                        },
                                        onDelete: function(item) {
                                            sous_familles.splice($.inArray(item.id, sous_familles), 1);
                                            chercherArticles('sous')
                                        },
                                    });
                                }
                            })
                        }
                        chercherArticles('')
                        function chercherArticles(from) {
                            if (from == 'famille')
                                sous_familles = []
                            $('#td_articles ul').remove()
                            $.ajax({
                                url: '{{path('gds_point_vente_get_article_reference')}}',
                                data: 'familles={"familles":' + JSON.stringify(familles) + ',"sous_familles":' + JSON.stringify(sous_familles) + '}&client_id=' + client_id,
                                datatype: 'json',
                                success: function(data) {
                                    $("#articles").tokenInput(data, {
                                        preventDuplicates: true,
                                        onAdd: function(item) {
                                            $('#token-input-articles').hide()
                                            if (!retour)
                                                article = getArticle(item.id, articles)
                                            else
                                                article = getArticle(item.id, retours)
                                            if (retour) {
                                                quantite_spinner = $('#article_quantite').spinner({
                                                    min: 0,
                                                    max: 99999999999,
                                                    step: 1,
                                                    places: item.unite.chiffre_virgule,
                                                    showOn: 'both'
                                                });
                                            }
                                            else if ((item.quantite_stock - item.quantite_min) > 0) {
                                                quantite_spinner = $('#article_quantite').spinner({
                                                    min: 0,
                                                    max: item.quantite_stock - item.quantite_min,
                                                    step: 1,
                                                    places: item.unite.chiffre_virgule,
                                                    showOn: 'both'
                                                });
                                            } else {
                                                quantite_spinner = $('#article_quantite').spinner({
                                                    min: 0,
                                                    max: 0,
                                                    step: 1,
                                                    places: item.unite.chiffre_virgule,
                                                    showOn: 'both'
                                                });
                                                item.quantite = 0
                                            }
                                            $('#article_quantite').change(function() {
                                                article.quantite = $(this).val()
                                            })
                                            if (!article) {
                                                article = new Object()
                                                article = JSON.parse(JSON.stringify(item));
                                                $('#article_quantite').val(article.quantite)
                                                $('#article_remise').val(article.remise)
                                                $('#article_id').val(article.id)
                                                $('#article_prix_ttc').val((article.prix_vente * (1 - article.remise / 100) * (1 + article.tva / 100)).toFixed(3))
                                            } else {
                                                $('#article_quantite').val(article.quantite)
                                                $('#article_remise').val(article.remise)
                                                $('#article_id').val(article.id)
                                                $('#article_prix_ttc').val((article.prix_vente * (1 - article.remise / 100) * (1 + article.tva / 100)).toFixed(3))
                                            }
                                            $('#article_remise').spinner({
                                                min: 0,
                                                max: article.remise_max,
                                                step: 1,
                                                places: 2,
                                                showOn: 'both'
                                            });
                                            $('#article_remise').change(function() {
                                                article.remise = $(this).val()
                                                $('#article_prix_ttc').val((article.prix_vente * (1 - article.remise / 100) * (1 + article.tva / 100)).toFixed(3))
                                            })
                                            $('#article_prix_ttc').spinner({
                                                min: article.prix_vente_min_ttc,
                                                max: 9999,
                                                step: 1,
                                                places: 3,
                                                showOn: 'both'
                                            });
                                            var remise = true
                                            $('#article_prix_ttc').change(function() {
                                                if ($(this).val() / (article.prix_vente * (1 + article.tva / 100)) > 1 && remise) {
                                                    $(this).val((article.prix_vente * (1 - article.remise / 100) * (1 + article.tva / 100)).toFixed(3))
                                                } else {
                                                    article.remise = (100 * (1 - ($(this).val() / (article.prix_vente * (1 + article.tva / 100))))).toFixed(2)
                                                    $('#article_remise').val(article.remise)
                                                }
                                            }
                                            )
                                            $('#article_quantite').focus()
                                        },
                                        onDelete: function(item) {
                                            $('#token-input-articles').show()
                                            article = new Object()
                                        },
                                    });
                                    $("html").removeClass("loadstate");
                                }
                            })
                        }
                        function getArticle(id, tab) {
                            for (i = 0; i < tab.length; i++) {
                                if (tab[i].id == id) {
                                    return tab[i]
                                }
                            }
                            return null
                        }
                    </script>
                </div>
            </div>
            <div style="margin-bottom: 0px" class="box">
                <div class="title">
                    <h4>
                        <span class="icon16 brocco-icon-grid"></span>
                        <span>Action</span>
                    </h4>
                </div>
                <div id="content_list_article" class="content">
                    <div class="row-fluid">



                        <div class="span4">
                            <div class="box">
                                <div class="title">
                                    <h4>
                                        <span class="icon16 brocco-icon-grid"></span>
                                        <span>Paiement</span>
                                    </h4>
                                </div>
                                <div id="content_list_article" class="content">
                                    <div class="row-fluid">
                                        <div class="span12">
                                            <a class="paiement" href="#paiement"><button class="btn"  style="width: 100%"><img src="/images/paiement/cash.png"/>Paiement</button></a>
                                        </div>
                                        <div class="span12">
                                            <a class="paiement_expresse" href="javascript:paiementExpresse()"><button class="btn"  style="width: 100%"><img src="/images/paiement/cash.png"/>Paiement Expresse</button></a>
                                        </div>

                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="span4">
                            <div class="box">
                                <div class="title">
                                    <h4>
                                        <span class="icon16 brocco-icon-grid"></span>
                                        <span>Charger Document</span>
                                    </h4>
                                </div>
                                <div id="content_list_article" class="content">
                                    <div class="row-fluid">
                                        <div class="span12">
                                            <a class="document_devis" href="#document_devis"><button class="btn"  style="width: 100%"><img src="/images/paiement/devis.png"/>Devis</button></a>
                                        </div>

                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="span4">
                            <div class="box">
                                <div class="title">
                                    <h4>
                                        <span class="icon16 brocco-icon-grid"></span>
                                        <span>Accompte</span>
                                    </h4>
                                </div>
                                <div id="content_list_article" class="content">
                                    <div class="row-fluid">
                                        <div class="span12">
                                            <a class="accompte" href="#accompte"><button class="btn"  style="width: 100%"><img src="/images/paiement/accompte.png"/>Accompte</button></a>
                                        </div>

                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div style='display:none'>
    <div id="accompte" style='padding:10px; background:#fff;'></div>
    <div id="retour" style='padding:10px; background:#fff;'></div>
    <div id="paiement" style='padding:10px; background:#fff;'></div>
    <div id="document_devis" style='padding:10px; background:#fff;'>

    </div>
    <div id="paiement_cheque" style='padding:10px; background:#fff;'>
    </div>
    <div id="paiement_cheque" style='padding:10px; background:#fff;'>
    </div>
    <div id="paiement_effet" style='padding:10px; background:#fff;'>
    </div>
    <div id="form-edit-body" style="text-align: center" class="modal-body">
        <form  id="form-montant-rendu" action="javascript:montantRendu()">
            <h1 style="font-size: 50px" >Total Net à payer :<span id="total_a_payer_espece" style="color: red;font-size: 50px"></span></h1>
            <h1 style="font-size: 50px">Montant Reçu : <input type="text" id="prix_montant_recu" value="0.000"/></h1>
            <div class="row-fluid">
                <button type="button" style="float: left" class="btn" onclick="javascript:addMontantRecu('5.000')" ><img src="/images/paiement/5.000.png" style="height: 50px"/>5.000</button>
                <button type="button" style="float: left" class="btn" onclick="javascript:addMontantRecu('10.000')" ><img src="/images/paiement/10.000.png" style="height: 50px"/>10.000</button>
                <button type="button" style="float: left" class="btn" onclick="javascript:addMontantRecu('20.000')" ><img src="/images/paiement/20.000.png" style="height: 50px"/>20.000</button>
                <button type="button" style="float: left" class="btn" onclick="javascript:addMontantRecu('50.000')" ><img src="/images/paiement/50.000.png" style="height: 50px"/>50.000</button>
            </div>
            <div class="form-actions">
                <button class="btn btn-info" type="submit">Valider</button>
                <button class="btn" onclick="$('#cboxClose').click()" type="button">Annuler</button>
            </div>
        </form>
    </div>
    <div id="form_retour" style="text-align: center" class="modal-body">
        <h1 style="font-size: 50px" >Montant Rendu :<span id="total_a_rendu_espece" style="color: red;font-size: 50px"></span></h1>
        <div class="form-actions">
            <button class="btn btn-info" onclick="retourArticle(true)" type="button">Transformée en Acompte</button>
            <button class="btn" onclick="retourArticle(false)" type="button">Retirer de caisse</button>
        </div>

    </div>

</div>

<script>
    $('#departement').val('{{app.user.departement.id}}')
    var fullDate = new Date();
    var twoDigitMonth = fullDate.getMonth()
    twoDigitMonth++
    twoDigitMonth += "";
    if (twoDigitMonth.length == 1)
        twoDigitMonth = "0" + twoDigitMonth;
    var twoDigitDate = fullDate.getDate() + "";
    if (twoDigitDate.length == 1)
        twoDigitDate = "0" + twoDigitDate;
    var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear();
    $("#date").val(currentDate)
    setInterval(time, 1000);
    function paiementExpresse(){
        paiement = new Object()
        paiement.type = 'Espece'
        paiement.montant =calculTotal().toFixed(3)
        paiements[0]=paiement
        saveRglememt()
    }
    function resetFormPaiement() {
        $('#numero_cheque').val('')
        $('#numero_acompte').val('')
        $('#numero_cheque_error').html('')
        $('#date_echeance').val('')
        $('#date_echeance_arror').html('')

        $('#montant_cheque').spinner("enable");
        var rest = calculTotal()
        for (var i = 0; i < paiements.length; i++) {
            rest = rest - parseFloat(paiements[i].montant)
        }
        $('#montant_cheque').val(rest.toFixed(3))
        $('#montant_cheque_error').html('')
        $('#compte_banquaire').html('')
        $('#compte_rib').val('')
        $('#compte_banque').val('')
        $('.form_compte_contenu').hide()
        $('.paiement_par_document').hide()
        $('.paiement_par_acompte').hide()

        $('#type_paiement option').each(function() {
            if ($(this).val() == 'espece')
                $(this).attr('selected', 'selected')
            else
                $(this).removeAttr('selected')
        })
    }
    function time() {
        var time = new Date($.now())
        h = time.getHours() // 0-24 format
        m = time.getMinutes()
        s = time.getSeconds()
        $('#heure').val(s + m * 60 + h * 3600)
        if (h < 10)
            h = '0' + h
        if (m < 10)
            m = '0' + m
        if (s < 10)
            s = '0' + s
        $('#now').val(h + ':' + m + ':' + s)
    }
    $('#departement').attr('disabled', 'disabled')
    a = 0
    $('.accompte').colorbox({
        inline: true,
        width: "50%",
        height: "90%",
        onOpen: function() {
            $.ajax({
                url: '{{path('gds_point_vente_accompte')}}',
                data: 'id=' + client_id,
                success: function(data) {
                    $('#accompte').html(data)
                    $('#date_echeance').datepicker()
                    $('#montant_accompte').spinner({
                        min: 0,
                        max: 999999,
                        step: 1,
                        places: 3,
                        showOn: 'both'
                    });
                    $('#montant_accompte').val('0.000')
                }
            })
        },
        onClosed: function() {
            $('#accompte').html('')
            initPage()
        }
    })
    $(".document_devis").colorbox({
        inline: true,
        width: "50%",
        height: "90%",
        onOpen: function() {
            $.ajax({
                url: '{{path('gds_vente_charge_devis')}}',
                data: 'client_id=' + client_id,
                success: function(data) {
                    $('#document_devis').html(data)
                }
            })
        }
        ,
        onComplete: function() {
            $('#total_a_rendu_espece').html((-calculTotal()).toFixed(3))
        },
        onCleanup: function() {

        },
        onClosed: function() {
            $('#paiement').html('')
        }
    });
    $(".paiement").colorbox({
        inline: true,
        width: "50%",
        height: "90%",
        onOpen: function() {
            if (articles.length == 0 && retours.length == 0) {
                $('#cboxClose').click()
                $('#client_error').remove()
                $.msgBox({
                    title: "Ticket de caisse",
                    content: "Ticket de caisse est vide",
                    type: "error",
                    buttons: [
                        {type: "cancel", value: "Annuler"}
                    ],
                });
            } else {

                if (calculTotal() > 0)
                    $.ajax({
                        url: '{{path('gds_vente_reglement_paiement')}}',
                        data: 'client_id=' + client_id,
                        success: function(data) {
                            $('#paiement').html(data)
                            $('#total_a_payer').html(calculTotal().toFixed(3))
                            $('#date_echeance').datepicker()
                            $('#montant_cheque').spinner({
                                min: 0,
                                max: 999999,
                                step: 1,
                                places: 3,
                                showOn: 'both'
                            });
                            $('#montant_cheque').val(calculTotal().toFixed(3))
                        }
                    })
                else {
                    $('#paiement').html($('#form_retour').html())
                    $('#form_retour').html('')
                }
            }
        }
        ,
        onComplete: function() {
            $('#total_a_rendu_espece').html((-calculTotal()).toFixed(3))
        },
        onCleanup: function() {
        },
        onClosed: function() {
            if (calculTotal() < 0)
                $('#form_retour').html($('#paiement').html())
            $('#paiement').html('')
            paiements = []
        }
    });
    $(".paiement_effet").colorbox({
        inline: true,
        width: "50%",
        height: "80%",
        onOpen: function() {
            if (client_id == -1) {
                $('#cboxClose').click()
                if ($('#client_error').length == 0) {
                    $('#client').after('<label class="error" id="client_error">Champ Obligatoire</label>')
                    $('#div_client .token-input-list').css('border', '1px solid red')
                }
                return false;
            } else {
                if (articles.length == 0) {
                    $('#cboxClose').click()
                    $('div_client .token-input-list').css('border', '')
                    $('#client_error').remove()
                    $.msgBox({
                        title: "Ticket de caisse",
                        content: "Ticket de caisse est vide",
                        type: "error",
                        buttons: [
                            {type: "cancel", value: "Annuler"}
                        ],
                    });
                } else {
                    $('.token-input-list').css('border', '')
                    $('#client_error').remove()

                    $.ajax({
                        url: '{{path('gds_reglement_effet')}}',
                        data: 'client_id=' + client_id,
                        success: function(data) {
                            $('#paiement_effet').html(data)
                            $('#total_a_payer_effet').html(calculTotal().toFixed(3))
                            $('#date_echeance').datepicker()
                            $('#montant_effet').spinner({
                                min: 0,
                                max: 999999,
                                step: 1,
                                places: 3,
                                showOn: 'both'
                            });
                            $('#montant_effet').val(calculTotal().toFixed(3))
                        }
                    })
                }
            }
        },
        onComplete: function() {

        },
        onCleanup: function() {

        },
        onClosed: function() {

        }
    });
    $(".paiement_cheque").colorbox({
        inline: true,
        width: "50%",
        height: "80%",
        onOpen: function() {
            if (client_id == -1) {
                $('#cboxClose').click()
                if ($('#client_error').length == 0) {
                    $('#client').after('<label class="error" id="client_error">Champ Obligatoire</label>')
                    $('div_client .token-input-list').css('border', '1px solid red')
                }
                return false;
            } else {
                if (articles.length == 0) {
                    $('.token-input-list').css('border', '')
                    $('#client_error').remove()
                    $('#cboxClose').click()
                    $.msgBox({
                        title: "Ticket de caisse",
                        content: "Ticket de caisse est vide",
                        type: "error",
                        buttons: [
                            {type: "cancel", value: "Annuler"}
                        ],
                    });
                } else {
                    $('div_client .token-input-list').css('border', '')
                    $('#client_error').remove()
                    $.ajax({
                        url: '{{path('gds_reglement_cheque')}}',
                        data: 'client_id=' + client_id,
                        success: function(data) {
                            $('#paiement_cheque').html(data)
                            $('#total_a_payer_cheque').html(calculTotal().toFixed(3))
                            $('#date_echeance').datepicker()
                            $('#montant_cheque').spinner({
                                min: 0,
                                max: 999999,
                                step: 1,
                                places: 3,
                                showOn: 'both'
                            });
                            $('#montant_cheque').val(calculTotal().toFixed(3))
                        }
                    })
                }
            }
        }
        ,
        onComplete: function() {

        },
        onCleanup: function() {

        },
        onClosed: function() {
            $('#paiement_cheque').html('')
        }
    });
    $(".paiement_espece").colorbox({
        inline: true,
        width: "50%",
        height: "80%",
        onOpen: function() {
            if (client_id == -1) {

                $('#cboxClose').click()
                if ($('#client_error').length == 0) {
                    $('#client').after('<label class="error" id="client_error">Champ Obligatoire</label>')
                    $('div_client .token-input-list').css('border', '1px solid red')
                }
                return false;
            } else {
                if (articles.length == 0) {
                    $('#cboxClose').click()
                    $('div_client .token-input-list').css('border', '')
                    $('#client_error').remove()
                    $.msgBox({
                        title: "Ticket de caisse",
                        content: "Ticket de caisse est vide",
                        type: "error",
                        buttons: [
                            {type: "cancel", value: "Annuler"}
                        ],
                    });
                } else {
                    $('.token-input-list').css('border', '')
                    $('#client_error').remove()
                    $('#paiement_espece').html($('#form-edit-body').html())
                    $('#form-edit-body').html('')
                }
            }

        },
        onComplete: function() {
            $('#prix_montant_recu').css('height', '32px')
            $('#prix_montant_recu').css('font-size', '30px')
            $('#prix_montant_recu').css('width', '223.167px')
            $('#total_a_payer_espece').html(calculTotal().toFixed(3))
            $('#prix_montant_recu').spinner({
                min: 0,
                max: 999999,
                step: 1,
                places: 3,
                showOn: 'both'
            });
            a++
            $('#prix_montant_recu').val('0.000')
        },
        onCleanup: function() {
            if (client_id != -1 && articles.length != 0) {
                $('#prix_montant_recu').attr('style', '')
                $('#prix_montant_recu').css('height', '32px')
                $('#prix_montant_recu').css('font-size', '30px')
                $('#prix_montant_recu').css('width', '223.167px')
                $('#form-montant-rendu').children('span').remove()
                $('#form-edit-body').html($('#paiement_espece').html())
                $('#paiement_espece').html('')
            }
        },
        onClosed: function() {

        }
    });
    $("#content_list_article").css('min-height', $("#content_form_article").css('height'))
    function accompte() {

        if ($('#type_accompte').val() != 'espece') {
            if ($('#compte_client').val() == '') {
                if ($('#compte_rib').val() == '' || $('#compte_banque').val() == '')
                {
                    $('#compte_banquaire').html('Ce champ est Obligatoire')
                    return false
                }
                else
                    $('#compte_banquaire').html('')
            }
            if ($('#numero_cheque').val() == '') {
                $('#numero_cheque_error').html('Ce champ est Obligatoire')
                return false
            } else {
                $('#numero_cheque_error').html('')
            }
            if ($('#date_echeance').val() == '') {
                $('#date_echeance_error').html('Ce champ est Obligatoire')
                return false
            } else {
                $('#date_echeance_error').html('')
            }
        }
        if ($('#montant_accompte').val() == '')
        {
            $('#montant_accompte_error').html('Ce champ est Obligatoire')
            return false
        } else {
            if (parseFloat($('#montant_accompte').val()) <= 0) {
                $('#montant_accompte_error').html('Il faut que ce champ est supérieur a 0')
                return false
            } else
                $('#montant_accompte_error').html('')
        }
        var accompte = new Object()
        accompte.type = $('#type_accompte option:selected').html()
        var td_type = '<td id="type_' + index + '">' + $('#type_accompte option:selected').html() + '</td>'
        if ($('#type_accompte').val() != 'espece')
        {
            accompte.compte = $('#compte_client').val()
            accompte.date = $('#date_echeance').val()
            accompte.numero = $('#numero_cheque').val()
            var td_numero = '<td id="numero_' + index + '">' + $('#numero_cheque').val() + '</td>'
            var td_date = '<td id="date_' + index + '">' + $('#date_echeance').val() + '</td>'
            var td_compte = '<td style="display: none"><input id="compte_id_' + index + '" type="hidden" value="' + $('#compte_client').val() + '" /></td>'
        } else {
            var td_numero = '<td id="numero_' + index + '">-</td>'
            var td_date = '<td id="date_' + index + '">-</td>'
            var td_compte = '<td style="display: none"></td>'
        }
        accompte.montant = $('#montant_accompte').val()
        accomptes[accomptes.length] = accompte
        var td_montant = '<td id="montant_' + index + '">' + $('#montant_accompte').val() + '</td>'
        $('#list_accompte').append('<tr>' + td_type + td_montant + td_numero + td_date + td_compte + '</td>' + '</tr>')
        if ($('#compte_rib').val() != '' || $('#compte_banque').val() != '')
        {
            $.ajax({
                dataType: 'json',
                url: '{{path('gds_vente_ajax_add_compte')}}',
                data: 'client_id=' + client_id + '&rib=' + $('#compte_rib').val() + '&banque=' + $('#compte_banque').val(),
                success: function(data) {
                    $('#compte_client').html(data.view)
                    $('#compte_id_' + index).val(data.compte_id)
                    index++
                }
            })
        }
        var total = 0
        for (var i = 0; i < accomptes.length; i++) {
            total = total + parseFloat(accomptes[i].montant)
        }
        $('#total_acompte').html(total.toFixed(3))
        resetFormAccompte()
    }
    function resetFormAccompte() {
        $('#numero_cheque').val('')
        $('#numero_cheque_error').html('')
        $('#date_echeance').val('')
        $('#date_echeance_arror').html('')
        $('#montant_accompte').val(0.000)
        $('#montant_accompte_error').html('')
        $('#compte_banquaire').html('')
        $('#compte_rib').val('')
        $('#compte_banque').val('')
        $('.form_compte_contenu').hide()
        $('.accompte_par_document').hide()
        $('.accompte_par_acompte').hide()

        $('#type_accompte option').each(function() {
            if ($(this).val() == 'espece')
                $(this).attr('selected', 'selected')
            else
                $(this).removeAttr('selected')
        })
    }
    function saveAccompte() {
        $.ajax({
            url: '{{path('gds_point_vente_save_accompte')}}',
            data: 'accomptes=' + JSON.stringify(accomptes) + '&client_id=' + client_id + '&heure=' + $('#heure').val()+ '&caisse_id=' + $('#caisse').val(),
            dataType: 'json',
            type: 'post',
            success: function(data) {
                if (data.success) {
                    $('#cboxClose').click()
                    $.msgBox({
                        title: "Acompte",
                        content: "Reference :" + data.acompte_reference + "<br>Montant :" + data.acompte_montant,
                        type: "info",
                    });
                }
            }

        })
    }
    function rglememt() {

        if ($('#type_paiement').val() != 'espece' && $('#type_paiement').val() != 'acompte') {
            if ($('#compte_client').val() == '') {
                if ($('#compte_rib').val() == '' || $('#compte_banque').val() == '')
                {
                    $('#compte_banquaire').html('Ce champ est Obligatoire')
                    return false
                }
                else
                    $('#compte_banquaire').html('')
            }
            if ($('#numero_cheque').val() == '') {
                $('#numero_cheque_error').html('Ce champ est Obligatoire')
                return false
            } else {
                $('#numero_cheque_error').html('')
            }
            if ($('#date_echeance').val() == '') {
                $('#date_echeance_error').html('Ce champ est Obligatoire')
                return false
            } else {
                $('#date_echeance_error').html('')
            }
        }
        if ($('#montant_cheque').val() == '')
        {
            $('#montant_cheque_error').html('Ce champ est Obligatoire')
            return false
        } else {
            if (parseFloat($('#montant_cheque').val()) <= 0) {
                $('#montant_cheque_error').html('Il faut que ce champ est supérieur a 0')
                return false
            } else
                $('#montant_cheque_error').html('')
        }
        paiement = new Object()
        paiement.type = $('#type_paiement option:selected').html()
        td_type = '<td id="type_' + index + '">' + $('#type_paiement option:selected').html() + '</td>'
        if ($('#type_paiement').val() != 'espece' && $('#type_paiement').val() != 'acompte')
        {
            paiement.compte = $('#compte_client').val()
            paiement.date = $('#date_echeance').val()
            paiement.numero = $('#numero_cheque').val()
            td_numero = '<td id="numero_' + index + '">' + $('#numero_cheque').val() + '</td>'
            td_date = '<td id="date_' + index + '">' + $('#date_echeance').val() + '</td>'
            td_compte = '<td style="display: none"><input id="compte_id_' + index + '" type="hidden" value="' + $('#compte_client').val() + '" /></td>'
        } else {
            td_numero = '<td id="numero_' + index + '">-</td>'
            td_date = '<td id="date_' + index + '">-</td>'
            td_compte = '<td style="display: none"></td>'
        }
        if ($('#type_paiement').val() == 'acompte') {
            paiement.acompte = $('#acompte_id').val()
        }
        paiement.montant = $('#montant_cheque').val()
        paiements[paiements.length] = paiement
        td_montant = '<td id="montant_' + index + '">' + $('#montant_cheque').val() + '</td>'
        $('#list_paiement').append('<tr>' + td_type + td_montant + td_numero + td_date + td_compte + '</td>' + '</tr>')
        if ($('#compte_rib').val() != '' || $('#compte_banque').val() != '')
        {
            $.ajax({
                dataType: 'json',
                url: '{{path('gds_vente_ajax_add_compte')}}',
                data: 'client_id=' + client_id + '&rib=' + $('#compte_rib').val() + '&banque=' + $('#compte_banque').val(),
                success: function(data) {
                    $('#compte_client').html(data.view)
                    $('#compte_id_' + index).val(data.compte_id)
                    index++
                }
            })
        } else
            index++
        resetFormPaiement()
    }
    function montantRendu() {

        var tab = new Array()
        saveTicketCaisse(montant_recu, montant_total, 'espece', tab)
    }
    function rglememtCheque() {
        if (valideFormCheque()) {
            var montant_recu = $('#montant_cheque').val()
            var montant_total = calculTotal().toFixed(3)
            $('#cboxClose').click()
            $.msgBox({
                title: "Montant Rendu",
                content: (montant_recu - montant_total).toFixed(3),
                type: "info",
                buttons: [{value: "OK"}],
                success: function(result) {

                }
            });
            var cheque = new Object()
            if ($('#compte_client').length == 1) {
                cheque.compte_client = $('#compte_client').val()
            }
            else {
                cheque.compte_client = ""
            }
            if ($('#numero_carte_identite').length == 1)
                cheque.numero_carte_identite = $('#numero_carte_identite').val()
            else
                cheque.numero_carte_identite = ""
            cheque.numero_cheque = $('#numero_cheque').val()
            cheque.date_echeance = $('#date_echeance').val()
            saveTicketCaisse(montant_recu, montant_total, 'cheque', cheque)
        }
    }
    function rglememtEffet() {
        if (valideFormCheque()) {
            var montant_recu = $('#montant_cheque').val()
            var montant_total = calculTotal().toFixed(3)
            $('#cboxClose').click()
            $.msgBox({
                title: "Montant Rendu",
                content: (montant_recu - montant_total).toFixed(3),
                type: "info",
                buttons: [{value: "OK"}],
                success: function(result) {

                }
            });
            var cheque = new Object()
            if ($('#compte_client').length == 1) {
                cheque.compte_client = $('#compte_client').val()
            }
            else {
                cheque.compte_client = ""
            }
            if ($('#numero_carte_identite').length == 1)
                cheque.numero_carte_identite = $('#numero_carte_identite').val()
            else
                cheque.numero_carte_identite = ""
            cheque.numero_cheque = $('#numero_cheque').val()
            cheque.date_echeance = $('#date_echeance').val()
            saveTicketCaisse(montant_recu, montant_total, 'effet', cheque)
        }
    }
    function valideFormEffet() {
        if ($('#numero_carte_identite').val() == '') {
            $('#numero_carte_identite_error').html('Cet champ est obligatoire')
            $('#numero_carte_identite').addClass('error')
            return false
        } else {
            $('#numero_carte_identite_error').html('')
            $('#numero_carte_identite').removeClass('error')
        }
        if ($('#numero_effet').val() == '') {
            $('#numero_effet_error').html('Cet champ est obligatoire')
            $('#numero_effet').addClass('error')
            return false
        } else {
            $('#numero_effet_error').html('')
            $('#numero_effet').removeClass('error')
        }
        if ($('#date_echeance').val() == '') {
            $('#date_echeance_error').html('Cet champ est obligatoire')
            $('#date_echeance').addClass('error')
            return false
        } else {
            $('#date_echeance_error').html('')
            $('#date_echeance').removeClass('error')
        }
        if (parseFloat($('#montant_effet').val()) <= 0) {
            $('#montant_effet_error').html('Il faut supérieur à 0')
            $('#montant_effet').addClass('error')
            return false
        } else {
            $('#montant_effet_error').html('')
            $('#montant_effet').removeClass('error')
        }
        return true
    }
    function valideFormCheque() {
        if ($('#numero_carte_identite').val() == '') {
            $('#numero_carte_identite_error').html('Cet champ est obligatoire')
            $('#numero_carte_identite').addClass('error')
            return false
        } else {
            $('#numero_carte_identite_error').html('')
            $('#numero_carte_identite').removeClass('error')
        }
        if ($('#numero_cheque').val() == '') {
            $('#numero_cheque_error').html('Cet champ est obligatoire')
            $('#numero_cheque').addClass('error')
            return false
        } else {
            $('#numero_cheque_error').html('')
            $('#numero_cheque').removeClass('error')
        }
        if ($('#date_echeance').val() == '') {
            $('#date_echeance_error').html('Cet champ est obligatoire')
            $('#date_echeance').addClass('error')
            return false
        } else {
            $('#date_echeance_error').html('')
            $('#date_echeance').removeClass('error')
        }
        if (parseFloat($('#montant_cheque').val()) <= 0) {
            $('#montant_cheque_error').html('Il faut supérieur à 0')
            $('#montant_cheque').addClass('error')
            return false
        } else {
            $('#montant_cheque_error').html('')
            $('#montant_cheque').removeClass('error')
        }
        return true
    }
    function saveRglememt() {
        if (paiements.length <= 0) {
            $.msgBox({
                title: "Reglement Client",
                content: "Il faut crée au moins un paiement",
                type: "error",
                buttons: [{value: "OK"}]
            });
        } else {
            var montant_total = calculTotal().toFixed(3)
            var montant_recu = 0
            var max_credit = limite_credit - solde
            for (var j = 0; j < paiements.length; j++) {
                montant_recu = montant_recu + parseFloat(paiements[j].montant)
            }
            if (client_id == 1 && montant_recu.toFixed(3) < montant_total) {
                $.msgBox({
                    title: "Reglement Client",
                    content: "C'est un client Passager Impossible de Passage <br> Reste a payer " + (montant_total - montant_recu).toFixed(3),
                    type: "error",
                    buttons: [{value: "OK"}]
                });
            } else {
                if (montant_recu.toFixed(3) < montant_total && (montant_total - montant_recu) > max_credit) {
                    var montant_depasse = (montant_total - montant_recu - max_credit).toFixed(3)
                    $.msgBox({
                        title: "Reglement Client",
                        content: "<input id='mdppp' type='password' /> </br>Dépassement Solde Limite avec " + montant_depasse,
                        type: "confirm",
                        buttons: [{value: "Valider"}, {value: "Retour"}],
                        afterShow: function() {
                            $('#mdppp').focus()
                        },
                        success: function(result) {
                            if (result == "Valider") {
                                if ($('#mdppp').val() != '') {
                                    $.ajax({
                                        url: "{{ path('gds_vente_quantite_depasse') }}",
                                        data: 'pass_quantite=' + $('#mdppp').val(),
                                        success: function(data) {
                                            if (data != 'failed') {
                                                $('#article_quantite').spinner({
                                                    min: 0,
                                                    max: 99999,
                                                    step: 1,
                                                    places: 2,
                                                    showOn: 'both'
                                                });
                                                $('#article_quantite').focus()
                                            }
                                        }
                                    })
                                }
                            }
                        }
                    });
                }
                else
                    $.ajax({
                        type: 'post',
                        url: '{{path('gds_save_ticket_caisse')}}',
                        dataType: 'json',
                        data: 'lignes=' + JSON.stringify(articles) + '&retours=' + JSON.stringify(retours) + '&paiements={"paiements":' + JSON.stringify(paiements) + '}&client_id=' + client_id + '&caisse_id=' + $('#caisse').val() + '&montat_ttc=' + montant_total + '&heure=' + $('#heure').val() + '&montant_recu=' + montant_recu,
                        success: function(data) {
                            if (data.success) {
                                $('#cboxClose').click();
                                if (montant_total < montant_recu && data.accompte)
                                    $.msgBox({
                                        title: "Reglement",
                                        content: "Enregistrement Effectué avec succés</br>Montant Rendu : " + (montant_recu - montant_total).toFixed(3),
                                        type: "info",
                                        buttons: [
                                            {value: "Retirer de caisse", style: "width :auto"},
                                            {value: "Transformée en Acompte", style: "width :auto"}
                                        ],
                                        success: function(result) {
                                            if (result == "Transformée en Acompte") {
                                                $.ajax({
                                                    url: '{{path('gds_point_vente_transforme_acompte')}}',
                                                    data: 'ticket_id=' + data.ticket_id + '&client_id=' + client_id + '&montant=' + (montant_recu - montant_total).toFixed(3) + '&heure=' + $('#heure').val(),
                                                    dataType: 'json',
                                                    success: function(data) {
                                                        if (data.success) {
                                                            $.msgBox({
                                                                title: "Acompte",
                                                                content: "Reference :" + data.acompte_reference + "<br>Montant :" + data.acompte_montant,
                                                                type: "info",
                                                            });
                                                        }

                                                    }
                                                })
                                            }
                                            initPage()
                                        }
                                    });
                                else
                                    $.msgBox({
                                        title: "Reglement",
                                        content: "Enregistrement Effectué avec succés",
                                        type: "info",
                                        buttons: [
                                            {value: "OK"}
                                        ],
                                        success: function(result) {
                                            initPage()
                                        }
                                    });
                            } else {
                                $.msgBox({
                                    title: "Reglement",
                                    content: "Erreur D'enregistrement",
                                    type: "error",
                                    buttons: [{value: "OK"}]
                                });
                            }
                        }
                    })
            }
        }
    }
    function saveTicketCaisse(montant_recu, montant_total, type, tab) {
        var montant_recu = $('#prix_montant_recu').val()
        var montant_total = $('#total_a_payer_espece').html()
        $.ajax({
            type: 'post',
            url: '{{path('gds_save_ticket_caisse')}}',
            data: 'lignes=' + JSON.stringify(articles) + '&client_id=' + client_id + '&caisse_id=' + $('#caisse').val() + '&montat_ttc=' + montant_total + '&heure=' + $('#heure').val() + '&montant_recu=' + montant_recu + '&type=' + type + '&info=' + JSON.stringify(tab),
            success: function(data) {
                if (data == 'suucess') {
                    $('#cboxClose').click();
                    if (montant_total < montant_recu)
                        $.msgBox({
                            title: "Reglement",
                            content: "Enregistrement Effectué avec succés</br>Montant Rendu : " + (montant_recu - montant_total).toFixed(3),
                            type: "info",
                            buttons: [{value: "OK"}],
                            success: function(result) {
                                initPage()
                            }
                        });
                } else {
                    $.msgBox({
                        title: "Reglement",
                        content: "Erreur D'enregistrement",
                        type: "error",
                        buttons: [{value: "OK"}]
                    });
                }
            }
        })
    }
    function addMontantRecu(val) {
        $('#prix_montant_recu').val((parseFloat($('#prix_montant_recu').val()) + parseFloat(val)).toFixed(3))
        $('#prix_montant_recu').focus()
    }
    function calculTotal() {
        var somme = 0
        for (var i = 0; i < articles.length; i++) {
            somme = somme + (articles[i].quantite * articles[i].prix_vente * (1 - (articles[i].remise / 100)) * (1 + (articles[i].tva / 100)))
        }
        for (var i = 0; i < retours.length; i++) {
            somme = somme - (retours[i].quantite * retours[i].prix_vente * (1 - (retours[i].remise / 100)) * (1 + (retours[i].tva / 100)))
        }
        return somme
    }
    function changerClient() {
        chercherArticles('')
        if ($('#gds_ventebundle_lignedevistype tr').length > 0 || $('#gds_vente_retour tr').length > 1)
            $.msgBox({
                title: "Chargement Remise",
                content: "Voulez-vous charger les remises du nouveau client ?",
                type: "confirm",
                buttons: [{value: "OUI"}, {value: "NON"}],
                success: function(result) {
                    if (result == "OUI") {
                        changeRemiseClient()
                    }
                }
            });
    }
    function changeRemiseClient() {
        var articles_to_modify = new Array();
        var retours_to_modify = new Array();
        for (var i = 0; i < articles.length; i++) {
            articles_to_modify[articles_to_modify.length] = articles[i].id
        }
        for (var i = 0; i < retours.length; i++) {
            retours_to_modify[retours_to_modify.length] = retours[i].id
        }
        $.ajax({
            url: '{{path("gds_vente_get_remises_client_point_vente")}}',
            type: "POST",
            data: {'articles': JSON.stringify(articles_to_modify), 'retours': JSON.stringify(retours_to_modify), 'client_id': $('#client').val()},
            dataType: 'json',
            success: function(data) {
                $('#gds_ventebundle_lignedevistype').html('')
                $('#gds_vente_retour').html('')
                for (i = 0; i < articles.length; i++) {
                    articles[i].remise = data.article[i].remise
                    article = articles[i]
                    if (retour)
                        $('#btn_retour').click()
                    addLigne(true)
                }
                for (i = 0; i < retours.length; i++) {
                    retours[i].remise = data.retour[i].remise
                    article = retours[i]
                    if (!retour)
                        $('#btn_retour').click()
                    addLigne(true)
                }
            }
        })
    }
    function editLigne(id) {
        retour = false
        $('#btn_retour').html(('Retour'))
        var i = stockSearch(articles, id);
        article = articles[i]
        $('#td_articles ul .token-input-token').remove()
        $('#td_articles ul').append('<li class="token-input-token">' +
                '<p>' + article.name + '</p>' +
                '<span class="token-input-delete-token">×</span>' +
                '</li>')
        $('#token-input-articles').hide()
        $('#article_code_barre').val(article.code_barre)
        $('#article_reference').val(article.label)
        $('#article_quantite').val(article.quantite)
        $('#article_remise').val(article.remise)
        $('#article_id').val(id)
        $('#article_quantite').focus();
    }
    function editLigneRetour(id) {
        retour = true
        $('#btn_retour').html(('Achat'))
        var i = stockSearch(retours, id);
        article = retours[i]
        $('#td_articles ul .token-input-token').remove()
        $('#td_articles ul').append('<li class="token-input-token">' +
                '<p>' + article.name + '</p>' +
                '<span class="token-input-delete-token">×</span>' +
                '</li>')
        $('#token-input-articles').hide()
        $('#article_code_barre').val(article.code_barre)
        $('#article_reference').val(article.label)
        $('#article_quantite').val(article.quantite)
        $('#article_remise').val(article.remise)
        $('#article_id').val(id)
        $('#article_quantite').focus();
    }

    function formArticleValide() {
        if (article.id == null) {
            if ($('#error_article').length == 0)
                $('#td_articles').after('<label  id="error_article" class="error"><label class="form-label span4"></label><label class="form-label span4 error" style="text-align:left;margin-left:0">Il faut sélectionner un article</label></label>')
            $('#td_articles .token-input-list').css('border', '1px solid red')
            return false
        } else {
            $('#error_article').remove()
            $('#td_articles .token-input-list').css('border', '')
        }
        if (parseFloat($('#article_quantite').val()) > 0) {
            $('#error_quantite').remove()
            $('#article_quantite').removeClass('error')
            return true

        } else {
            if ($('#error_quantite').length == 0) {
                $('#article_quantite').addClass('error')
                $('#div_article_quantite').after('<label  id="error_quantite" class="error"><label class="form-label span4 error" style="text-align:left;margin-left:0">Il faut que ce champ supérieur a 0</label></label>')
            }
            return false
        }


    }
    function addLigne(k) {
        if (!retour)
        {
            if (k) {
                var i = stockSearch(articles, article.id);
                if (i == -1)
                    articles[articles.length] = article
                if ($('#ligne_ticket_' + $('#article_id').val()).length == 0) {
                    $('#gds_ventebundle_lignedevistype').append('<tr id="ligne_ticket_' + article.id + '">' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')" class="numero"></td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + article.reference + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + article.designation + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + article.quantite + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + article.remise + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + ((article.prix_vente * article.quantite) * (1 - article.remise / 100) * (1 + article.tva / 100)).toFixed(3) + '</td>' +
                            '<td style="padding:0;cursor: pointer;" ><img src="/images/icons/delete.png"  onclick="deleteLigne(' + article.id + ')"></td>' +
                            '</tr>')
                } else {
                    $('#ligne_ticket_' + $('#article_id').val()).replaceWith('<tr id="ligne_ticket_' + article.id + '">' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')" class="numero"></td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + article.reference + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + article.designation + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + article.quantite + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + article.remise + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + ((article.prix_vente * article.quantite) * (1 - article.remise / 100) * (1 + article.tva / 100)).toFixed(3) + '</td>' +
                            '<td style="padding:0;cursor: pointer;" ><img src="/images/icons/delete.png"  onclick="deleteLigne(' + article.id + ')"></td>' +
                            '</tr>')
                }
                refrechTotal()
                refrecheNumero()
                resetFormArticle()
            } else
            if (formArticleValide()) {
                var i = stockSearch(articles, article.id);
                if (i == -1)
                    articles[articles.length] = article
                if ($('#ligne_ticket_' + $('#article_id').val()).length == 0) {
                    $('#gds_ventebundle_lignedevistype').append('<tr id="ligne_ticket_' + article.id + '">' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')" class="numero"></td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + article.reference + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + article.designation + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + article.quantite + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + article.remise + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + ((article.prix_vente * article.quantite) * (1 - article.remise / 100) * (1 + article.tva / 100)).toFixed(3) + '</td>' +
                            '<td style="padding:0;cursor: pointer;" ><img src="/images/icons/delete.png"  onclick="deleteLigne(' + article.id + ')"></td>' +
                            '</tr>')
                } else {
                    $('#ligne_ticket_' + $('#article_id').val()).replaceWith('<tr id="ligne_ticket_' + article.id + '">' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')" class="numero"></td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + article.reference + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + article.designation + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + article.quantite + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + article.remise + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigne(' + article.id + ')">' + ((article.prix_vente * article.quantite) * (1 - article.remise / 100) * (1 + article.tva / 100)).toFixed(3) + '</td>' +
                            '<td style="padding:0;cursor: pointer;" ><img src="/images/icons/delete.png"  onclick="deleteLigne(' + article.id + ')"></td>' +
                            '</tr>')
                }
                refrechTotal()
                refrecheNumero()
                resetFormArticle()
            }
        }
        else {
            if (k) {
                var i = stockSearch(retours, article.id);
                if (i == -1) {
                    article.noir = 0;
                    retours[retours.length] = article
                }
                if ($('#ligne_ticket_retour_' + $('#article_id').val()).length == 0) {
                    $('#gds_vente_retour').append('<tr id="ligne_ticket_retour_' + article.id + '">' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')" class="numero"></td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + article.reference + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + article.designation + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + article.quantite + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + article.remise + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + ((article.prix_vente * article.quantite) * (1 - article.remise / 100) * (1 + article.tva / 100)).toFixed(3) + '</td>' +
                            '<td style="padding:0;cursor: pointer;" ><img src="/images/icons/delete.png"  onclick="deleteLigneRetour(' + article.id + ')">   <img src="/images/icons/black.png" style="width:16px"  onclick="retourNoir(' + article.id + ')"></td>' +
                            '</tr>')
                } else {
                    $('#ligne_ticket_retour_' + $('#article_id').val()).replaceWith('<tr id="ligne_ticket_retour_' + article.id + '">' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')" class="numero"></td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + article.reference + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + article.designation + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + article.quantite + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + article.remise + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + ((article.prix_vente * article.quantite) * (1 - article.remise / 100) * (1 + article.tva / 100)).toFixed(3) + '</td>' +
                            '<td style="padding:0;cursor: pointer;" ><img src="/images/icons/delete.png"  onclick="deleteLigneRetour(' + article.id + ')">   <img src="/images/icons/black.png" style="width:16px" onclick="retourNoir(' + article.id + ')"></td>' +
                            '</tr>')
                }
                refrechTotal()
                refrecheNumero()
                resetFormArticle()
            } else
            if (formArticleValide()) {
                var i = stockSearch(retours, article.id);
                if (i == -1) {
                    article.noir = 0;
                    retours[retours.length] = article
                }
                if ($('#ligne_ticket_retour_' + $('#article_id').val()).length == 0) {
                    $('#gds_vente_retour').append('<tr id="ligne_ticket_retour_' + article.id + '">' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')" class="numero"></td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + article.reference + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + article.designation + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + article.quantite + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + article.remise + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + ((article.prix_vente * article.quantite) * (1 - article.remise / 100) * (1 + article.tva / 100)).toFixed(3) + '</td>' +
                            '<td style="padding:0;cursor: pointer;" ><img src="/images/icons/delete.png"  onclick="deleteLigneRetour(' + article.id + ')">   <img src="/images/icons/black.png" style="width:16px" onclick="retourNoir(' + article.id + ')"></td>' +
                            '</tr>')
                } else {
                    $('#ligne_ticket_retour_' + $('#article_id').val()).replaceWith('<tr id="ligne_ticket_retour_' + article.id + '">' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')" class="numero"></td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + article.reference + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + article.designation + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + article.quantite + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + article.remise + '</td>' +
                            '<td style="cursor: pointer;" onclick="editLigneRetour(' + article.id + ')">' + ((article.prix_vente * article.quantite) * (1 - article.remise / 100) * (1 + article.tva / 100)).toFixed(3) + '</td>' +
                            '<td style="padding:0;cursor: pointer;" ><img src="/images/icons/delete.png"  onclick="deleteLigneRetour(' + article.id + ')">   <img src="/images/icons/black.png" style="width:16px" onclick="retourNoir(' + article.id + ')"></td>' +
                            '</tr>')
                }
                refrechTotal()
                refrecheNumero()
                resetFormArticle()
            }
        }
    }
    function retourNoir(id) {
        if (retours[stockSearch(retours, id)].noir == 0) {
            $('#ligne_ticket_retour_' + id).attr('bgcolor', '#353535')
            $('#ligne_ticket_retour_' + id + ' td').css('color', '#ffffff')
            retours[stockSearch(retours, id)].noir = 1;
        }
        else {
            retours[stockSearch(retours, id)].noir = 0;
            $('#ligne_ticket_retour_' + id).removeAttr('bgcolor')
            $('#ligne_ticket_retour_' + id + ' td').css('color', '#000')
        }
    }
    function refrechTotal() {
        var total = 0
        var tva = 0;
        var remise = 0
        var quantite = 0
        for (var i = 0; i < articles.length; i++) {
            quantite = quantite + parseFloat(articles[i].quantite)
            remise = remise + (articles[i].quantite * articles[i].prix_vente * (articles[i].remise / 100))
            tva = tva + (articles[i].quantite * articles[i].prix_vente * (1 - (articles[i].remise / 100)) * (articles[i].tva / 100))
            total = total + (articles[i].quantite * articles[i].prix_vente * (1 - (articles[i].remise / 100)) * (1 + (articles[i].tva / 100)))
        }
        for (var i = 0; i < retours.length; i++) {
            quantite = quantite - parseFloat(retours[i].quantite)
            remise = remise - (retours[i].quantite * retours[i].prix_vente * (retours[i].remise / 100))
            tva = tva - (retours[i].quantite * retours[i].prix_vente * (1 - (retours[i].remise / 100)) * (retours[i].tva / 100))
            total = total - (retours[i].quantite * retours[i].prix_vente * (1 - (retours[i].remise / 100)) * (1 + (retours[i].tva / 100)))
        }
        $('#quantite_total').html(quantite.toFixed(1))
        $('#tva_total').html(tva.toFixed(3))
        $('#remise_total').html(remise.toFixed(3))
        $('#ttc_total').html(total.toFixed(3))
    }
    function resetFormArticle() {
        $('#token-input-articles').show()
        $('#td_articles ul .token-input-token').remove()
        $('#article_quantite').val('')
        $('#article_remise').val('')
        $('#article_prix_ttc').val('')
        $('#token-input-articles').focus();
    }
    function deleteLigne(id) {
        $('#ligne_ticket_' + id).remove()
        var i = stockSearch(articles, id);
        articles.splice(i, 1)
        refrechTotal()
        refrecheNumero()
    }
    function deleteLigneRetour(id) {
        $('#ligne_ticket_retour_' + id).remove()
        var i = stockSearch(retours, id);
        retours.splice(i, 1)
        refrechTotal()
        refrecheNumero()
    }
    function refrecheNumero() {
        var i = 1
        $('.numero').each(function() {
            $(this).html(i)
            i++
        })
    }
    function retourArticle(type) {
        var montant_total = calculTotal().toFixed(3)
        $.ajax({
            type: 'post',
            url: '{{path('gds_save_ticket_caisse')}}',
            dataType: 'json',
            data: 'lignes=' + JSON.stringify(articles) + '&retours=' + JSON.stringify(retours) + '&client_id=' + client_id + '&caisse_id=' + $('#caisse').val() + '&montat_ttc=' + montant_total + '&heure=' + $('#heure').val() + '&type=' + type,
            success: function(data) {
                if (data.success) {
                    $('#cboxClose').click();
                    initPage()
                    $.msgBox({
                        title: "Acompte",
                        content: "Reference :" + data.acompte_reference + "<br>Montant :" + data.acompte_montant,
                        type: "info",
                    });
                } else {
                    $.msgBox({
                        title: "Reglement",
                        content: "Erreur D'enregistrement",
                        type: "error",
                        buttons: [{value: "OK"}]
                    });
                }

            }
        })
    }
    function initPage() {
        retour = false
        $('#btn_retour').html(('Retour'))
        articles = []
        paiements = []
        accomptes=[]
        retours = []
        client_id = 1
        $('#client').jqxComboBox({selectedIndex: 0});

        $('#gds_ventebundle_lignedevistype').html('')
        $('#gds_vente_retour').html('')
        refrechTotal()
    }

</script>